import {
    useStore
} from 'vuex';
import Cookies from 'js-cookie';
import {
    useRoute,
    useRouter
} from 'vue-router';
import {
    reactive
} from '@vue/reactivity';
import {
    onMounted
} from '@vue/runtime-core';
import {
    apiService
} from '../../api/apiService';
import {
    userSignUp,
    vercodeAjax,
    forgetPwd,
    registerVercodeAjax,
    pcPhoneLogin,
    pcAccountLogin
} from '../../api/server';
import {
    showConfirm,
    showSuccess,
    showError
} from '../../util/MessageDeal';
import {
    encrypted
} from '../../util/ServerLang';
import {
    selfI18n
} from '../../i18n/index';
import md5 from 'js-md5';

export function LoginSetup () {
    const loginstate = reactive({
        origin: ''
    });
    const store = useStore();
    const route = useRoute();
    const router = useRouter();

    const setUserInfo = (userinfo, token) => {
        let userinfo_cookies = {};
        if (userinfo.username) {
            userinfo_cookies = {
                phone: userinfo.phone,
                openid: userinfo.openid,
                vercode: userinfo.vercode,
                locale: userinfo.language,
                username: userinfo.username,
                NCCLOUD_TOKEN: token || userinfo.token,
                password: userinfo.password,
                timezone: userinfo.timezone,
                roles: userinfo.roles && userinfo.roles.join(','),
                _id: userinfo._id
            };
            if (userinfo.roles && userinfo.roles.length === 0) {
                userinfo_cookies = {
                    ...userinfo_cookies,
                    address: userinfo.address,
                    company: userinfo.company,
                    email: userinfo.email,
                    name: userinfo.name,
                    names: userinfo.names
                };
                console.log(userinfo_cookies);
            }
        } else if (userinfo.openid) {
            userinfo_cookies = { ...userinfo };
        } else {
            return false;
        }
        store.commit('SET_USER_INFO', userinfo_cookies);
        saveUserInfoToCookies(userinfo_cookies);
    };

    const getCurrentOriginPath = () => {
        let fullpath = route.query.origin;
        fullpath = (fullpath === '/' || fullpath === undefined) ? store.state.indexpage : fullpath;
        return fullpath;
    };

    const sendMessage = (phone) => {
        apiService({
            api: vercodeAjax,
            param: {
                phone,
                lang: 'cn'
            },
            success: () => {
                showSuccess(selfI18n('wp_Send_verification_code_successfully'));
            }
        });
    };

    const getOpenID = () => {
        loginstate.opneid = route.query.openid || Cookies.get('openid');
        if (!loginstate.opneid) {
            if (process.env.NODE_ENV === 'production') {
                location.href = '/weixin/login/v2';
            } else {
                showError(selfI18n('wp_Current_development_environment_miss_openid'));
            }
        }
    };

    const loginByPhone = (phone, vercode) => {
        const loginfrom = getLoignFrom();
        apiService({
            api: pcPhoneLogin,
            param: {
                phone: phone,
                vercode: vercode,
                loginfrom,
                openid: loginstate.opneid
            },
            success: data => {
                // 全部转移到stater里进行重新获取用户信息进行存储设置
                setUserInfo(data.value, data.token);
                router.push(`/starter?openid=${loginstate.opneid}&origin=${loginstate.origin}`);
            }
        });
    };
    const loginByAccount = (account, password) => {
        const loginfrom = getLoignFrom();

        apiService({
            api: pcAccountLogin,
            param: {
                username: account,
                loginfrom,
                password: md5(password),
                openid: loginstate.opneid
            },
            success: data => {
                setUserInfo(data.value, data.token);
                router.push(`/starter?openid=${loginstate.opneid}&origin=${loginstate.origin}`);
            }
        });
    };
    const saveUserInfoToCookies = (userinfo) => {
        const day = new Date();
        day.setTime(day.getTime() + 7 * 24 * 60 * 60 * 1000);
        for (const key in userinfo) {
            if (key === 'password') {
                Cookies.set('NCCLOUD_MQTP', encrypted(userinfo[key]), {
                    expires: 7
                });
            } else {
                Cookies.set(key, userinfo[key], {
                    expires: 7
                });
            }
        }
    };
    const getLoignFrom = () => {
        let loginfrom = route.query.loginfrom;
        if (loginfrom) {
            Cookies.set('loginfrom', loginfrom);
        }
        loginfrom = Cookies.get('loginfrom');
        return loginfrom;
    };
    onMounted(() => {
        loginstate.origin = getCurrentOriginPath();
    });
    return {
        loginstate,
        loginByPhone,
        loginByAccount,
        sendMessage,
        getOpenID,
        getLoignFrom,
        getCurrentOriginPath,
        setUserInfo
    };
}
export function RegisterSetup () {
    const register_form = reactive({
        username: '',
        names: '',
        company: '',
        addr: '',
        phone: '',
        email: '',
        password: '',
        language: 'cn',
        vercode: '',
        cpass: ''
    });
    const Router = useRouter();

    const commitRegister = () => {
        apiService({
            api: userSignUp,
            param: {
                ...register_form,
                password: md5(register_form.password)
            },
            success: () => {
                showSuccess(selfI18n('sign_up_success'));
                Router.push({
                    path: '/login'
                });
            }
        });
    };
    const sendMessage = (phone) => {
        apiService({
            api: registerVercodeAjax,
            param: {
                phone,
                email: '',
                lang: 'cn'
            },
            success: () => {
                showSuccess(selfI18n('wp_Send_verification_code_successfully'));
            }
        });
    };
    return {
        sendMessage,
        register_form,
        commitRegister
    };
}

export function ForgetPwdSetup () {
    const forget_form = reactive({
        addr: '',
        phone: '',
        password: '',
        language: 'cn',
        vercode: '',
        cpass: ''
    });

    const Router = useRouter();

    const commitResetPassowrd = () => {
        const {
            phone,
            vercode,
            cpass
        } = forget_form;
        apiService({
            api: forgetPwd,
            param: {
                phone,
                newpassword: md5(cpass),
                vercode
            },
            success: () => {
                showSuccess(selfI18n('wp_Successfully_retrieved_your_password_and_will_return_to_the_login_page'));
                Router.push({
                    path: '/login'
                });
            }
        });
    };

    return {
        forget_form,
        commitResetPassowrd
    };
}

export function LogoutSetup () {
    const router = useRouter();
    const LogoutMehod = () => {
        Cookies.remove('openid');
        Cookies.remove('password');
        Cookies.remove('NCCLOUD_MQTP');
        Cookies.remove('NCCLOUD_TOKEN');
        Cookies.remove('username');
        Cookies.remove('vercode');
        Cookies.remove('phone');
        Cookies.remove('roles');

        router.push({
            path: '/login'
        });
    };
    const Logout = () => {
        showConfirm(selfI18n('log_out_tip'), LogoutMehod);
    };

    return {
        LogoutMehod,
        Logout
    };
}
